<?php
namespace app\admin\controller;

use \think\Controller;
//use think\facade\Request;
use think\Db;
use think\facade\Request;
use think\captcha\Captcha;

class Index extends  Controller
{
	public function aaa(){
		
		Db::name('manager')->select();
	}
	public function logout()
	{
		session(null);
		$this->success('登出成功', 'admin/index/index');
	}
	public function verify()
    {
		$config =    [
			'imageH'=>40,		    // 验证码字体大小
		    'fontSize'    =>    24,    
		    // 验证码位数
		    'length'      =>    3,   
		    // 关闭验证码杂点
		    'useNoise'    =>    false, 
		];
		$captcha = new Captcha($config);
		return $captcha->entry();
    }
    public function index()
    {
    	
		if(Request::isPost())
		{
			$post = input('post.');
			//登陆数据验证
			$this->logindatavali($post);
			//查询用户并返回
			$userinfo = $this->checklive($post);
			//查询用户并判断时候存在
			$this->islive($userinfo);

		}
		
    	return $this->fetch();
    }
	
	
	
	protected function islive($userinfo)
	{
			if(!empty($userinfo))
			{
				//查询用户时候冻结
				$this->isfreeze($userinfo);
				session('managerinfo', $userinfo);
				$this->success('登录成功', 'admin/welcome/index');
			}else
			{
				$this->error('登录失败，用户名或密码错误','/admin/index/index');
			}
			exit;				
	}
	protected function isfreeze($userinfo)
	{
		if($userinfo['freeze']!=1)
		{
			$this->error('该用户已冻结,请充值后登陆','admin/index/index');exit;
		}
	}
	
	//查询用户是否存在
	protected function checklive($post)
	{
			$manager_name = $post['manager_name'];
			$passwd= $post['passwd'] ;
			$re = Db::name('manager')
			->where('manager_name',$manager_name)
			->where('passwd',$passwd)
			->find();
			return $re;
	}
	
	//用于验证数据
	protected function logindatavali($post)
	{
		//验证验证码
		$validate = $post['validate'];
		$this->validatecheck($validate);
		//验证用户名和密码
		$usernameandpasswd = [
		    'username'  => $post['manager_name'],
		    'passwd' => $post['passwd']
		];
		$this->usernameandpasswd($usernameandpasswd);
	}
	//验证码确认
	protected function validatecheck($validate)
	{

		$captcha = new Captcha();
		if(!$captcha->check($validate))
		{
			// 验证失败
			$this->error('验证码错误','admin/index/index');exit;
		}		
	}
	//用户名密码校验
	protected function usernameandpasswd($usernameandpasswd)
	{
		$validate = new \app\admin\validate\Managervali;
		$result = $validate->check($usernameandpasswd);
		if(!$result){
			// 验证失败
			$this->error($validate->getError(),'admin/index/index');exit;
		   
		}		
	}
}
